package com.vincce.fitness.core.interceptor;

import com.vincce.fitness.constant.Constant;
import com.vincce.fitness.core.base.RedisRunner;
import com.vincce.fitness.core.base.UserSessionHolder;
import com.vincce.fitness.core.util.CheckUtil;
import com.vincce.fitness.core.util.HttpUtil;
import com.vincce.fitness.entity.User;
import com.vincce.fitness.entity.UserSession;
import com.vincce.fitness.mappers.core.UserMapper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
/**
 * Created by henry on 4/9/14.
 */
public class UserSessionInterceptor extends HandlerInterceptorAdapter {

	@Resource
	RedisRunner redisRunner;

	@Resource
	UserMapper userMapper;

	private static final String COOKIE_KEY = "p";

	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response,
							 Object handler) throws Exception {
		String cookieValue = HttpUtil.getCookie(request, COOKIE_KEY);
		if (CheckUtil.isEmpty(cookieValue)) {
			cookieValue = UUID.randomUUID().toString();
		}
		String openId = null;
		String oauthOpenId = null;
		UserSession userSession = null;
		if (!CheckUtil.isEmpty(cookieValue)) {
			userSession = redisRunner.cacheGet(Constant.REDIS_DB_USER_SESSION, cookieValue, UserSession.class);
		}
		UserSession oauthUserSession = UserSessionHolder.get();
		if (oauthUserSession != null) {
			oauthOpenId = oauthUserSession.getOpenId();
		}
		if (userSession != null) {
			openId = userSession.getOpenId();
		}
		if (oauthOpenId == null && openId == null) {
            HttpUtil.removeCookie(response, COOKIE_KEY);
			throw new RuntimeException("Unknown OpenId!");
		}
		if (oauthOpenId != null && openId == null || oauthOpenId != null && !oauthOpenId.equals(openId)) {
			userSession = oauthUserSession;
			openId = oauthOpenId;
		}

		if (userSession == null || userSession.getUserId() == null || CheckUtil.isEmpty(userSession.getK())) {
            userSession = new UserSession();
			User user = userMapper.findUserByOpenId(openId);
            userSession.setUserId(user.getId());
            userSession.setOpenId(openId);
			// 然后存到redis
			userSession.setK(cookieValue);
			redisRunner.cacheAddUpdate(Constant.REDIS_DB_USER_SESSION, cookieValue, userSession, Constant.REDIS_USER_SESSION_EXPIRY);
		}
		UserSessionHolder.put(userSession);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		UserSession userSession = UserSessionHolder.get();
		redisRunner.cacheAddUpdate(Constant.REDIS_DB_USER_SESSION, userSession.getK(), userSession, Constant.REDIS_USER_SESSION_EXPIRY);
		HttpUtil.addCookie(response, COOKIE_KEY, userSession.getK(), Constant.REDIS_USER_SESSION_EXPIRY);
		super.postHandle(request, response, handler, modelAndView);
	}
}

